package com.bankcard.bininfo.trie;

import com.bankcard.util.RedisClient;
import redis.clients.jedis.Pipeline;

public class RedisTrieStorage implements TrieStorage {
    private final RedisClient redisClient;
    private static final String TRIE_KEY = "trie";

    public RedisTrieStorage(RedisClient redisClient) {
        this.redisClient = redisClient;
    }

    @Override
    public void insertIntoTrie(String bin) {
        try (Pipeline pipeline = redisClient.pipelined()) {
            StringBuilder key = new StringBuilder();
            for (char c : bin.toCharArray()) {
                key.append(c);
                pipeline.hset(TRIE_KEY, key.toString(), "1");
            }
            pipeline.sync();
        }
    }

    @Override
    public String findLongestMatch(String accountNumber) {
        String longestMatch = "";
        StringBuilder key = new StringBuilder();
        
        for (char c : accountNumber.toCharArray()) {
            key.append(c);
            if (redisClient.hexists(TRIE_KEY, key.toString())) {
                longestMatch = key.toString();
            } else {
                break;
            }
        }

        return longestMatch.isEmpty() ? null : longestMatch;
    }
}